<template>
    <el-row>
        <el-col :span="12" :offset="6">
            <div v-show="basicInfo">
                <el-form ref="userForm" :rules="rules" :model="form" label-width="100px" align="center">
                    <el-form-item label="头像" prop="avatar">
                        <el-image style="width: 100px; height: 100px"
                                  :preview-src-list="[form.avatar]"
                                  :src="form.avatar" fit="fill" :preview-teleported="true" />
                        <br/>
                        <el-upload
                                ref="uploadRef"
                                class="upload-demo"
                                :action="uploadUrl"
                                :auto-upload="false"
                                list-type="picture"
                                :before-upload="beforeUpload"
                                :on-success = onSuccess
                                :on-error = onError
                        >
                            <template #trigger>
                                <el-button type="primary">选择文件</el-button>
                            </template>

                            <el-button class="ml-3" type="success" @click="submitUpload">
                                上传
                            </el-button>

                            <template #tip>
                                <div class="el-upload__tip">
                                    JPG,PNG,BMP,GIF 格式，文件大小不能大于1MB!
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username" style="width: 50%" >
                        <el-input v-model="form.username" disabled/>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender" style="width: 50%">
                        <el-select v-model="form.gender" placeholder="请选择性别" >
                            <MySelectOption typeCode = "gender"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickName" style="width: 50%" >
                        <el-input v-model="form.nickName" disabled/>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile" style="width: 50%">
                        <el-input v-model="form.mobile"/>
                    </el-form-item>
                    <el-form-item label="地址" prop="address" >
                        <el-input v-model="form.address" type="textarea" resize="none" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" @click="updateUser">更新</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-show="!basicInfo">
                <el-form ref="passwordForm" :rules="pwdRules" :model="pwdform" label-width="100px" align="center">
                    <el-form-item label="旧密码" prop="oldPassword" style="width: 50%">
                        <el-input v-model="pwdform.oldPassword" show-password />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword" style="width: 50%">
                        <el-input v-model="pwdform.newPassword" show-password/>
                    </el-form-item>
                    <el-form-item label="重复密码" prop="reNewPassword" style="width: 50%" >
                        <el-input v-model="pwdform.reNewPassword" show-password/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" @click="updatePassword">更新</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-button-group style="width: 100%;height:20px;font-size: 16px;">
                <el-button style="width: 50%;height:35px;"  @click="toUpdateUser">更新信息</el-button>
                <el-button style="width: 50%;height:35px;" @click="toUpdatePassword">更新密码</el-button>
            </el-button-group>
        </el-col>
    </el-row>
</template>

<script setup>
    import {ref,reactive,onMounted,computed} from 'vue'
    import MySelectOption from '@/components/common/MySelectOption.vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'

    let userForm = ref(null)
    let passwordForm = ref(null)
    let uploadRef = ref(null)
    let basicInfo = ref(true)
    const rules = reactive({
        gender: [{required: true,message: '请选择性别', trigger: 'blur'},],
        address: [{required: true,message: '请输入地址', trigger: 'blur'},],
        mobile: [{required: false,type:'number', message: '手机号格式有误', trigger: 'change', transform:(value)=>Number(value)}
                 ],
    })
    const pwdRules = reactive({
        oldPassword: [{required: true, message: '请输入旧密码', trigger: 'blur'},],
        newPassword: [{required: true, message: '请输入新密码', trigger: 'blur'},],
        reNewPassword: [{required: true, message: '请再次输入新密码', trigger: 'blur'},],
    })
    let form = reactive({})
    let pwdform = reactive({})

    onMounted(function () {
        let item = sessionStorage.getItem("user");
        let user = JSON.parse(item)
        request.get(`/api/common/getUser/${user.id}`).then(resp => {
            for(let key in resp){
                form[key] = resp[key]
            }
        })
    })
    let uploadUrl = computed(()=>{
        return "/api/common/upload/avatar"
    })
    function updateUser(){
        userForm.value.validate((valid, fields)=>{
            if(valid) {
                request.post("/api/common/updateUser", form).then(resp => {
                    ElMessage({message: '修改信息成功！',type: 'success'})
                })
            }else{
                ElMessage({message: '缺少必填项！',type: 'error'})
            }
        })
    }
    function updatePassword(){
        passwordForm.value.validate((valid, fields)=>{
            if(valid) {
                if(pwdform.newPassword === pwdform.oldPassword){
                    ElMessage({message: '新密码不能与旧密码相同！',type: 'error'})
                    return
                }
                if(pwdform.newPassword !== pwdform.reNewPassword){
                    ElMessage({message: '两次输入新密码不一致！',type: 'error'})
                    return
                }
                pwdform.userId = form.id
                request.post("/api/common/updatePassword", pwdform).then(resp => {
                    ElMessage({message: '修改密码成功！',type: 'success'})
                })
            }else{
                ElMessage({message: '缺少必填项！',type: 'error'})
            }
        })
    }

    function toUpdateUser() {
        basicInfo.value = true
    }
    function toUpdatePassword() {
        basicInfo.value = false
    }

    const beforeUpload = (rawFile) => {
        if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png'
            && rawFile.type !== 'image/bmp'&& rawFile.type !== 'image/gif') {
            ElMessage.error('必须是 JPG,PNG,BMP,GIF 格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 1) {
            ElMessage.error('文件大小不能大于1MB!')
            return false
        }
        return true
    }

    function submitUpload(){
        uploadRef.value.submit()
    }
    function onSuccess(response, uploadFile, uploadFiles){
        console.log(response.data)
        ElMessage.success('上传成功,更新后生效!')
        form.avatar = response.data
        uploadRef.value.clearFiles()
    }
    function onError(error, uploadFile, uploadFiles){
        console.log(error)
    }
</script>

<style scoped>

</style>